package com.example.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;

import com.example.fragment.databinding.FragmentTitleBinding;

public class TitleFragment extends Fragment {
    private static final String MESSAGE_KEY = "msg_key";
    private FragmentTitleBinding binding;
    private String msg;

    public TitleFragment() {
        // Required empty public constructor
    }

    public static TitleFragment newInstance() {
        TitleFragment fragment = new TitleFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentTitleBinding.inflate(inflater, container, false);

        // 设置结果监听器
        getParentFragmentManager().setFragmentResultListener("key", this,
                new FragmentResultListener() {
                    @Override
                    public void onFragmentResult(@NonNull String key, @NonNull Bundle bundle) {
                        String result = bundle.getString("title");
                        binding.tvTitle.setText(result);
                    }
                });
        // 接收Activity传递的参数
        Bundle bundle = getArguments();
        if (bundle != null) {
            binding.tvTitle.setText(bundle.getString(MESSAGE_KEY));
        }
        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (this.msg != null) {
            binding.tvTitle.setText(this.msg);
        }
    }

    // 从外界接收信息
    public void receiveMsg(String msg) {
        // 在此方法中不要直接访问UI控件
        this.msg = msg;
    }
}